package org.groovyflow.util

class ClosureHelp{

    /**This ain't ruby, where an argument array is automatically
    *coalesced into arg0, arg1, arg2 etc.   Is there anyway to handle this
    *more nicely in groovy?
    * WARNING!! If you want to pass args into a Closure that expects a
    * List (e.g. {theList -> println theList.size()  }
    * you can't actually have args = theList.  That's
    * becuase we'll pass in the first element of theList.
    * So instead you need args = [theList].  That is,
    * you need to put theList inside a list.
    */
    static def invokeClosure(clos, args){
        if(clos.getMaximumNumberOfParameters() == 0)
            return clos()
        else if(clos.getMaximumNumberOfParameters() == 1){
            if(args instanceof List)
                return clos(args[0])
            else 
                return clos(args)
        }
        else if(clos.getMaximumNumberOfParameters() == 2)
             return clos(args[0], args[1])
        else if(clos.getMaximumNumberOfParameters() == 3)
             return clos(args[0], args[1], args[2])
        else if(clos.getMaximumNumberOfParameters() == 4)
             return clos(args[0], args[1], args[2], args[3])
        else if(clos.getMaximumNumberOfParameters() == 5)
             return clos(args[0], args[1], args[2], args[3], args[4])
        else if(clos.getMaximumNumberOfParameters() == 6)
             return clos(args[0], args[1], args[2], args[3], args[4], args[5])
        else if(clos.getMaximumNumberOfParameters() == 7)
             return clos(args[0], args[1], args[2], args[3], args[4], args[5], args[6])
        else
            throw new UnsupportedOperationException("We only handle up to 7 arguments")
    }
}